package com.chuangjiangx.member.basic.web.controller;


import com.chuangjiangx.commons.exception.BaseException;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.member.coupon.web.response.response.UploadedFileResponse;
import com.chuangjiangx.publicmodule.domain.upload.service.UploadFileService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传下载接口
 */
@RestController
@RequestMapping(value = "/h5/file",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
public class UploadController extends BaseController {

    @Autowired
    private UploadFileService uploadFileService;

    /**
     * 上传图片
     * @param file 文件
     * @return com.chuangjiangx.commons.response.CamelResponse
     * @throws Exception
     * @see UploadedFileResponse
     */
    @ApiOperation(value = "上传图片接口", httpMethod = "GET")
    @RequestMapping(value = "/upload")
    public Response upload(MultipartFile file) throws Exception {
//        CheckImage.chekcImage(file);//校验上传的图片
        String fileKey = uploadFileService.uploadFile(file.getInputStream(), file.getOriginalFilename());
        UploadedFileResponse response = new UploadedFileResponse(fileKey,uploadFileService.getDownloadUrl(fileKey));
        return ResponseUtils.successCamel(response);
    }

    /**
     * 下载图片
     * @param key oss或fastDFS 图片key
     * @return com.chuangjiangx.commons.response.CamelResponse
     * @see UploadedFileResponse
     */
    @RequestMapping(value = "/dowload")
    public Response download(String key) {
        String url = uploadFileService.getDownloadUrl(key);
        if (StringUtils.isBlank(url)) {
            throw new BaseException("-1","文件不存在");
        }
        return ResponseUtils.successCamel(new UploadedFileResponse(key,url));
    }
}
